﻿@using System.IO;
@using Microsoft.AspNetCore.Components.Web.Extensions

<h1>File preview</h1>

<InputFile OnChange="LoadFiles" id="input-file" multiple /><br />

@if (isLoading)
{
    <p>Loading...</p><br />
}

@foreach (var (file, content) in loadedFiles)
{
    <p id="file-@(file.Name)">
        <strong>File name:</strong> @(file.Name)<br />
        <strong>File size (bytes):</strong> <span id="file-size">@(file.Size)</span><br />
        <strong>File content:</strong> <span id="file-content">@content</span><br />
    </p>
}

<h1>Image upload</h1>

<InputFile OnChange="LoadImage" id="input-image" /><br />

@if (imageDataUri != null)
{
    <p>
        Uploaded image:<br />
        <img id="image-uploaded" src="@imageDataUri" />
    </p>
}

<p>
    Source image:<br />
    <img id="image-source" src="images/blazor_logo_1000x.png" />
</p>

@code {
    Dictionary<IBrowserFile, string> loadedFiles = new Dictionary<IBrowserFile, string>();

    bool isLoading;

    string imageDataUri;

    async Task LoadFiles(InputFileChangeEventArgs e)
    {
        isLoading = true;
        loadedFiles.Clear();

        foreach (var file in e.Files)
        {
            StateHasChanged();

            using var reader = new StreamReader(file.OpenReadStream());

            loadedFiles.Add(file, await reader.ReadToEndAsync());
        }

        isLoading = false;
    }

    async Task LoadImage(InputFileChangeEventArgs e)
    {
        var file = e.Files.SingleOrDefault();

        if (file != null)
        {
            var format = "image/jpeg";
            var imageFile = await file.ToImageFileAsync(format, 640, 480);

            using var fileStream = imageFile.OpenReadStream();
            using var memoryStream = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream);

            imageDataUri = $"data:{format};base64,{Convert.ToBase64String(memoryStream.ToArray())}";
            StateHasChanged();
        }
    }
}
